import {
  LockOutlined,
  MobileOutlined,
  UserOutlined,
} from '@ant-design/icons';
import {
  LoginForm,
  ProFormCaptcha,
  ProFormText,
} from '@ant-design/pro-components';
import {
  Helmet,
  history
} from '@umijs/max';
import { Alert, App, Tabs } from 'antd';
import { createStyles } from 'antd-style';
import React, { useState, useEffect } from 'react';
import { Footer } from '@/components';
import { login, getCaptcha, getSysInfo } from '@/services/api';
import { sm2 } from 'sm-crypto-v2';
import Settings from '../../../../config/defaultSettings';

const useStyles = createStyles(({ token }) => {
  return {
    action: {
      marginLeft: '8px',
      color: 'rgba(0, 0, 0, 0.2)',
      fontSize: '24px',
      verticalAlign: 'middle',
      cursor: 'pointer',
      transition: 'color 0.3s',
      '&:hover': {
        color: token.colorPrimaryActive,
      },
    },
    lang: {
      width: 42,
      height: 42,
      lineHeight: '42px',
      position: 'fixed',
      right: 16,
      borderRadius: token.borderRadius,
      ':hover': {
        backgroundColor: token.colorBgTextHover,
      },
    },
    container: {
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      overflow: 'auto',
      backgroundImage:
        "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
      backgroundSize: '100% 100%',
    },
    'login-content-code': {
      opacity: 1,
    },
    'login-content-code-expired': {
      opacity: 0.7,
      filter: 'grayscale(1)',
    },
    'login-content-code-img': {
      width: '100%',
      height: '100%',
      borderRadius: 4,
    },
  };
});



const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => {
  return (
    <Alert
      style={{
        marginBottom: 24,
      }}
      message={content}
      type="error"
      showIcon
    />
  );
};

const Login: React.FC = () => {
  const [userLoginState, setUserLoginState] = useState<API.LoginResult>({});
  const [type, setType] = useState<string>('account');
  const { styles } = useStyles();
  const { message } = App.useApp();
  
  // 系统信息状态，用于存储SM2公钥
  const [sysInfo, setSysInfo] = useState<Record<string, any>>({});
  
  // 验证码相关状态
  const [captchaImage, setCaptchaImage] = useState<string>('');
  const [captchaId, setCaptchaId] = useState<number | undefined>(undefined);
  const [captchaLoading, setCaptchaLoading] = useState<boolean>(false);
  const [expirySeconds, setExpirySeconds] = useState<number>(60);
  const [timer, setTimer] = useState<NodeJS.Timeout | null>(null);
  
  // 加载验证码
  const loadCaptcha = async () => {
    try {
      setCaptchaLoading(true);
      const data = await getCaptcha();
      console.log('获取验证码:', data);
      if (data.code !== 200) {
        message.error('获取验证码失败，请重试');
        return;
      }
      if (data.result.img && data.result.id) {
        // 智能判断是否需要添加base64前缀
        let imageSrc = data.result.img;
        if (typeof imageSrc === 'string' && !imageSrc.startsWith('data:image')) {
          imageSrc = `data:image/png;base64,${imageSrc}`;
        }
        
        setCaptchaImage(imageSrc);
        setCaptchaId(data.result.id);
        setExpirySeconds(data.result.expirySeconds || 60);
        
        // 清除之前的计时器
        if (timer) {
          clearInterval(timer);
        }
        
        // 设置新的计时器
        const newTimer = setInterval(() => {
          setExpirySeconds((prev) => {
            if (prev <= 1) {
              if (timer) clearInterval(timer);
              return 0;
            }
            return prev - 1;
          });
        }, 1000);
        
        setTimer(newTimer);
      }
    } catch (error) {
      console.error('获取验证码失败:', error);
      message.error('获取验证码失败，请重试');
    } finally {
      setCaptchaLoading(false);
    }
  };
  
  // 组件挂载时先加载系统信息和SM2公钥，然后再加载验证码
  useEffect(() => {
    const initialize = async () => {
      try {
        // 先加载系统信息和SM2公钥
        const sysInfoData = await getSysInfo();
        console.log('系统信息:', sysInfoData);
        // 保存系统信息，包括SM2公钥
        if (sysInfoData.code === 200 && sysInfoData.result) {
          setSysInfo(sysInfoData.result);
          // 如果有公钥，缓存到localStorage
          if (sysInfoData.result) {
            localStorage.setItem('SysInfo', JSON.stringify(sysInfoData.result));
          }
        }
        // 然后加载验证码
        await loadCaptcha();
      } catch (error) {
        console.error('初始化失败:', error);
        // 即使加载系统信息失败，也尝试加载验证码
        await loadCaptcha();
      }
    };
    
    initialize();
    
    // 组件卸载时清除计时器
    return () => {
      if (timer) {
        clearInterval(timer);
      }
    };
  }, []);

  const handleSubmit = async (values: any & { code?: string }) => {
    try {
      if (!captchaId) {
        message.error('请先获取验证码');
        return;
      }
      
      if (!values.code) {
        message.error('请输入验证码');
        return;
      }
      
      // 转换参数格式：r1项目的LoginParams -> v1项目的LoginInput 
      const loginData = {
        account: values.account,
        password: values.password,
        // 登录模式设置为账号密码登录 
        loginMode: 0, // 0表示账号密码登录模式 
        // 其他可选参数 
        host: '', // 租户域名，默认为空 
        codeId: captchaId,
        code: values.code
      };
      
      // 获取SM2公钥，优先从sysInfo状态中获取，其次从localStorage中获取
      let publicKey: any = '';
      
      // 1. 优先从当前加载的系统信息中获取公钥
      if (sysInfo.publicKey) {
        publicKey = sysInfo.publicKey;
      }
      // 2. 如果状态中没有，从localStorage获取缓存的公钥
      else {
        // 从localStorage获取SysInfo字符串
        const sysInfoStr = localStorage.getItem('SysInfo');
        // 解析SysInfo字符串为对象
        const sysInfoObj = sysInfoStr ? JSON.parse(sysInfoStr) : {};
        publicKey = sysInfoObj.publicKey || '';
      }
      
      // SM2加密密码
      if (publicKey) {
        const encryptedPassword = sm2.doEncrypt(loginData.password, publicKey, 1);
        loginData.password = encryptedPassword;
      } else {
        console.warn('未获取到SM2公钥，使用明文密码登录');
      }
      
      // 登录，传递转换并加密后的参数
      const msg:any = await login(loginData);
      
      // 增强的登录成功判断逻辑，适配不同的后端返回格式
      if (msg.code === 200) {
        // 存储token到localStorage
        if (msg.result?.accessToken) {
          localStorage.setItem('accessToken', msg.result.accessToken);
        } else {
          console.warn('登录成功但未获取到accessToken:', msg);
        }
        
        message.success('登录成功！');
        
        // 尝试获取用户信息和菜单数据，但即使失败也继续跳转
        // 注释掉空的try-catch块，避免lint错误
        
        // 强制跳转到首页，确保登录成功后一定会跳转到正确的页面
        const urlParams = new URL(window.location.href).searchParams;
        const redirectUrl = urlParams.get('redirect') || '/';
        // 直接使用window.location.href进行跳转
        window.location.href = redirectUrl;
        return;
      }
      message.error(msg.message || '登录失败，请重试！');
      // 如果失败去设置用户错误信息
      setUserLoginState(msg);
      // 重新获取验证码
      loadCaptcha();
    } catch (error: any) {
      console.error('登录异常:', error);
        message.error(error.message || '登录失败，请重试！');
      // 重新获取验证码
      loadCaptcha();
    }
  };
  const { status, type: loginType } = userLoginState;

  return (
    <div className={styles.container}>
      <Helmet>
        <title>
          登录页
          {Settings.title && ` - ${Settings.title}`}
        </title>
      </Helmet>

      <div
        style={{
          flex: '1',
          padding: '32px 0',
        }}
      >
        <LoginForm
          contentStyle={{
            minWidth: 280,
            maxWidth: '75vw',
          }}
          logo={<img alt="logo" src="/round.png" />}
          title="智能客服系统"
          initialValues={{
            autoLogin: true,
          }}
          onFinish={async (values) => {
            await handleSubmit(values as any);
          }}
        >
          <Tabs
            activeKey={type}
            onChange={setType}
            centered
            items={[
              {
                key: 'account',
                label: '账户密码登录',
              },
              // {
              //   key: 'mobile',
              //   label: '手机号登录',
              // },
            ]}
          />

          {status === 'error' && loginType === 'account' && (
            <LoginMessage
              content='账户或密码错误(admin/ant.design)'
            />
          )}
          {type === 'account' && (
            <>
              <ProFormText
                name="account"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined />,
                }}
                placeholder='请输入用户名'
                rules={[
                    {
                      required: true,
                      message: '请输入用户名!',
                    },
                  ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                }}
                placeholder='请输入密码'
                rules={[
                    {
                      required: true,
                      message: '请输入密码！',
                    },
                  ]}
              />
              <div style={{ display: 'flex', gap: 12 }}>
                <ProFormText
                  name="code"
                  fieldProps={{
                    size: 'large',
                    prefix: <LockOutlined />,
                    maxLength: 4,
                  }}
                  placeholder='请输入验证码'
                  rules={[
                    {
                      required: true,
                      message: '请输入验证码！',
                    },
                  ]}
                  style={{ flex: 1 }}
                />
                <div 
                  className={expirySeconds > 0 ? 'login-content-code' : 'login-content-code-expired'} 
                  onClick={loadCaptcha}
                  style={{
                    width: 130,
                    height: 38,
                    cursor: 'pointer'
                  }}
                >
                  {captchaLoading ? (
                    <div style={{ width: '100%', height: '100%', textAlign: 'center', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                      <span>加载中...</span>
                    </div>
                  ) : (
                    <img 
                      width="100%" 
                      height="100%" 
                      src={captchaImage} 
                      alt="验证码" 
                      style={{ cursor: 'pointer' }}
                    />
                  )}
                </div>
              </div>
            </>
          )}

          {status === 'error' && loginType === 'mobile' && (
            <LoginMessage content="验证码错误" />
          )}
          {type === 'mobile' && (
            <>
              <ProFormText
                fieldProps={{
                  size: 'large',
                  prefix: <MobileOutlined />,
                }}
                name="mobile"
                placeholder='手机号'
                rules={[
                  {
                    required: true,
                    message: '请输入手机号！',
                  },
                  {
                    pattern: /^1\d{10}$/,
                    message: '手机号格式错误！',
                  },
                ]}
              />
              <ProFormCaptcha
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                }}
                captchaProps={{
                  size: 'large',
                }}
                placeholder='请输入验证码'
                captchaTextRender={(timing, count) => {
                  if (timing) {
                    return `${count} 获取验证码`;
                  }
                  return '获取验证码';
                } }
                name="captcha"
                rules={[
                  {
                    required: true,
                    message: '请输入验证码！',
                  },
                ]} onGetCaptcha={(_mobile: string): Promise<void> => {
                  throw new Error('Function not implemented.');
                } }                // onGetCaptcha={async (phone) => {
                //   const result = await getFakeCaptcha({
                //     phone,
                //   });
                //   if (!result) {
                //     return;
                //   }
                //   message.success('获取验证码成功！验证码为：1234');
                // }}
              />
            </>
          )}
        </LoginForm>
      </div>
      <Footer />
    </div>
  );
};

export default Login;
